package com.example.demo.controller;


import com.example.demo.entity.Article;
import com.example.demo.repository.ArticleRepository;
import com.example.demo.result.ExceptionMsg;
import com.example.demo.result.Response;
import com.example.demo.result.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("article")
public class ArticleController {
    protected Response result(ExceptionMsg mas){
        return new Response(mas);
    }
    protected  Response result(){
        return new Response();
    }
    @Autowired
    private ArticleRepository articleRepository;
    @RequestMapping(value = "/",method = RequestMethod.GET)
    public ResponseData getArticleList(){
        List<Article> list=new ArrayList<Article>( articleRepository.findAll());
        return new ResponseData(ExceptionMsg.SUCCESS,list);
    }

    /**
     * 增加
     */
    @RequestMapping(value = "/",method =RequestMethod.POST )
    public ResponseData add(Article article){
        articleRepository.save(article);

        return new ResponseData(ExceptionMsg.SUCCESS,article);
    }
    /**
     * 删除
     */
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public ResponseData delete(@PathVariable("id")long id){
        articleRepository.deleteById(id);
        return new ResponseData(ExceptionMsg.SUCCESS,"");
    }
    /**
     * 改
     */
    @RequestMapping(value = "/{id}",method = RequestMethod.PUT)
    public ResponseData update(Article article){
        articleRepository.save(article);
        return new ResponseData(ExceptionMsg.SUCCESS,article);
    }

    /**
     * 查
     */
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public ResponseData findArticle(@PathVariable("id")Integer id)throws IOException{
        Article article=articleRepository.findById(id);
        if(article!=null){
            return new ResponseData(ExceptionMsg.SUCCESS,article);
        }
        return new ResponseData(ExceptionMsg.FAILED,article);
    }

}
